package com.newflypig.jblog.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.geetest.sdk.java.GeetestLib;
import com.newflypig.jblog.model.BlogConfig;
import com.newflypig.jblog.util.BlogUtils;

public class GeetestFilter extends UsernamePasswordAuthenticationFilter{
	
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		String username = request.getParameter("jblog_username");
		String password = request.getParameter("jblog_password");
		
		if(BlogUtils.isEmpty(username, password)){
			throw new UsernameNotFoundException("用户名、密码不能为空！");
		}
		
		
		GeetestLib gtSdk = new GeetestLib(BlogConfig.GEETEST_AK, BlogConfig.GEETEST_SK);
        
        String challenge = request.getParameter("geetest_challenge");
        String validate  = request.getParameter("geetest_validate");
        String seccode   = request.getParameter("geetest_seccode");
        
        Integer status = (Integer) request.getSession().getAttribute(GeetestLib.SERVER_STATUS_SESSION_KEY);
        
        //根据Geetest的官方说明，如果Geetest服务器宕机，需要切换到本地验证，暂时这边不设本地验证，Geetest宕机直接通过。
        if(status == 1){
	        if(BlogUtils.isEmpty(challenge,validate,seccode) || gtSdk.enhencedValidateRequest(challenge, validate, seccode) == 0 ){
	        	System.out.println("未通过人机识别");
	        	request.getSession().setAttribute("exceptionMsg", "未通过人机识别");
	        	throw new UsernameNotFoundException("人机识别失败，请检查您的行为！");
	        }
        }
        
		return super.attemptAuthentication(request, response);
	}
}
